package cn.edu.zafu.bigdata.x.zyy;

import java.util.Scanner;
import java.util.Random;

public class GuessNumberGame {
    private static final Random random = new Random();

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            int maxAttempts = 7; // 可以限定最大次数
            System.out.println("欢迎来到猜数字游戏！你有 " + maxAttempts + " 次机会。");
            System.out.print("请输入一个1到100之间的数字：");

            int numberToGuess = random.nextInt(100) + 1; // 随机生成一个1到100之间的数字
            int attempts = 0;
            int userGuess;

            while (attempts < maxAttempts) {
                if (scanner.hasNextInt()) {
                    userGuess = scanner.nextInt();
                    attempts++;
                    if (userGuess == numberToGuess) {
                        System.out.println("恭喜你！猜对了数字 " + numberToGuess + "！");
                        break;
                    } else if (userGuess < numberToGuess) {
                        System.out.println("太小了，请再试一次。");
                    } else {
                        System.out.println("太大了，请再试一次。");
                    }
                } else {
                    System.out.println("请输入一个有效的整数！");
                    scanner.next(); // 清除错误的输入
                }
            }

            if (attempts == maxAttempts) {
                System.out.println("很遗憾，机会用完了。正确答案是 " + numberToGuess + "。");
            }

            System.out.print("要再玩一次吗？(yes/no): ");
            if (!scanner.next().equalsIgnoreCase("yes")) {
                break;
            }
            scanner.nextLine(); // 清除换行符
        }
        scanner.close();
        System.out.println("感谢你玩猜数字游戏，再见！");
    }
}